package com.sencorsta.ids.common.service;

import com.alibaba.fastjson.JSONObject;
import com.sencorsta.ids.core.log.Out;
import com.sencorsta.utils.string.CodeUtil;
import com.sencorsta.utils.string.StringUtil;
import io.netty.handler.codec.http.FullHttpRequest;
import org.apache.commons.lang3.RandomStringUtils;

public class TokenService implements RedisService {

    public static String validate(FullHttpRequest request) {
        try {
            String token = request.headers().get("Access-Token");
            if (StringUtil.isEmpty(token)) {
                return null;
            }
            String tokenStr = CodeUtil.decode(token);
            JSONObject tokenObj=JSONObject.parseObject(tokenStr);
            String userId=tokenObj.getString("userId");
            String tokenOld = R_SYSTEM.get("token:"+userId);
            if (StringUtil.isEmpty(tokenOld)) {
                return null;
            }
            if (!tokenOld.equals(token)){
                return null;
            }
            R_SYSTEM.expire("token:" + userId, 30 * 60);
            return userId;
        } catch (Exception e) {
            Out.error(e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    public static String setToken(String userId) {
        try {
            JSONObject json = new JSONObject();
            json.put("userId", userId);
            json.put("ranStr", RandomStringUtils.randomAlphanumeric(16));
            json.put("time", System.currentTimeMillis());
            String token = CodeUtil.encode(json.toJSONString());
            R_SYSTEM.set("token:" + userId, token);
            R_SYSTEM.expire("token:" + userId, 30 * 60);
            return token;
        } catch (Exception e) {
            Out.error(e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

}
